/**
 * 按秒倒计时功能，需要传入that对象，对象中需要声明countDown{}对象
 * 如果大于24小时，则直接返回 xx天xx小时XX分，没分倒计时，如果小于24小时，则每秒更新倒计时
 * @param  {[type]} startDate [倒计时开始时间，可为空，为空则以now()为开始时间]
 * @param  {[type]} endDate   [倒计时结束时间，必填项]
 * @param  {[type]} that      [倒计时对象，必填项]
 * @param  {[type]} uniqueId  [唯一ID，必填项]
 * @return {[type]}           [setCountDown{uniqueId:countDownString}]
 */
function countDown(startDate, endDate, that, uniqueId) {
  if (null == startDate || '' == startDate || undefined == startDate || 'undefined' == startDate)
    startDate = new Date();
  else if (!(startDate instanceof Date)) {
    var temp = startDate;
    startDate = new Date();
    startDate.setTime(temp);
  }
  if (!(endDate instanceof Date)) {
    var temp = endDate;
    endDate = new Date();
    endDate.setTime(temp);
  }
  var leftTime = endDate.getTime() - startDate.getTime();
  if (leftTime <= 0) {//已结束
    setCountDown(that, uniqueId, '已结束');
    return;
  }
  var leftsecond = parseInt(leftTime / 1000);
  var day = Math.floor(leftsecond / (60 * 60 * 24));
  var hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600);
  var minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60);
  var second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
  if (leftsecond > 3600 * 24) {
    var time = day + "天" + hour + "小时" + minute + "分钟";
    setCountDown(that, uniqueId, time);
    setTimeout(function () {
      countDown(new Date(), endDate, that, uniqueId);
    }, 1000 * 60)
    //return;
  } else {
    var time = hour + "小时" + minute + "分钟" + second + "秒";
    setCountDown(that, uniqueId, time);
    setTimeout(function () {
      countDown(new Date(), endDate, that, uniqueId);
    }, 1000)
  }
}

//为countDown赋值
function setCountDown(that, uniqueId, time) {
  var paramName = "countDown." + uniqueId;
  that.setData({
    [paramName]: time
  })
}

/**
 * 根据已知秒数倒计时
 * @param  {[type]} second   [倒计时秒数，必填项]
 * @param  {[type]} that      [倒计时对象，必填项]
 * @param  {[type]} uniqueId  [唯一ID，必填项]
 * @return {[type]}           [回调函数that.countDownFinish(uniqueId)]
 */
function countDownSecond(secondInt,that, uniqueId){
  if(secondInt<=0){
    try{
      setCountDown(that, uniqueId, '已结束');
      that.countDownFinish(uniqueId);
    }catch(e){}
    return;
  }
  var leftsecond = secondInt;
  var day = Math.floor(leftsecond / (60 * 60 * 24));
  var hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600);
  var minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60);
  var second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
  var time = hour + "小时" + minute + "分钟" + second + "秒";
  if(leftsecond < 3600 )
    time = minute + "分钟" + second + "秒";
  setCountDown(that, uniqueId, time);
  setTimeout(function () {
      countDownSecond(--secondInt, that, uniqueId);
  }, 1000)
}

module.exports = {
  countDown: countDown,
  countDownSecond:countDownSecond
}
